<template>
  <div class="user-container">
    <common-dialog></common-dialog>
    <!--嵌套表单的dialog-->
    <el-dialog :title="modalType===0?'添加用户':'编辑用户'"
               class="user-dialog"
               :show-close="false"
               :visible.sync="dialogFormVisible">
      <el-form :model="addUserForm"
               class="user-form"
               ref="ruleForm"
               :rules="rules">
        <el-form-item label="姓名"
                      prop="name">
          <el-input v-model="addUserForm.name"
                    class="user-form-name"></el-input>
        </el-form-item>
        <el-form-item label="地址"
                      prop="address">
          <el-select v-model="addUserForm.address"
                     class="user-form-address"
                     placeholder="请选择活动区域">
            <el-option label="区域一"
                       value="shanghai"></el-option>
            <el-option label="区域二"
                       value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <h1>{{ addUserForm }}</h1>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary"
                   @click="addNewUser('ruleForm')">确 定
        </el-button>
      </div>

    </el-dialog>
    <div class="user-func">
      <el-button class="user-add"
                 @click="openDialog(0)"
                 type="primary">+新增
      </el-button>

      <div class="user-search">
        <el-form ref="form"
                 class="user-search-form"
                 :model="searchedForm">
          <el-form-item>
            <el-input v-model="searchedForm.name"
                      @clear="handleClearUserName"
                      clearable
                      class="user-search-data"
                      placeholder="请输入要搜索的姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="user-search-btn"

                       @click="handleSearchUserName(searchedForm.name)"
                       type="primary">搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="user-table">
      <el-table
          border
          stripe
          :data="tableData"
          style="width: 100%">
        <el-table-column
            type="index"
            label="id"
            width="180">
        </el-table-column>
        <el-table-column
            prop="date"
            label="日期"
            width="180">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="180">
        </el-table-column>
        <el-table-column
            prop="address"
            label="地址">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row,1)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

  </div>

</template>

<script>
import {addUser, getUserData, deleteUser, editUser} from "@/api";
import CommonDialog from "@/components/CommonDialog";

export default {
  components: {CommonDialog},
  data() {
    return {
      //要添加的新用户信息
      addUserForm: {
        id: 0,
        date: '',
        name: '',
        address: ''
      },


      //要查询的信息
      searchedForm: {
        name: ''
      },

      tableData: [],

      dialogFormVisible: false,

      //表单是添加表单还是编辑表单,0表示添加，1表示编辑
      modalType: 0,

      //表单验证规则
      rules: {
        name: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在3到20个字符', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入用住址', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在3到20个字符', trigger: 'blur'}
        ]
      },


    }
  },
  mounted() {
    this.getUserList();


    this.getCurrentDate()

  },
  methods: {
    //打开对话框
    openDialog(modalType) {
      this.modalType = modalType
      this.dialogFormVisible = true

    },
    //获取当前的年月日并且设置给addUserForm
    getCurrentDate() {
      const currentDate = new Date();

      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');

      this.addUserForm.date = `${year}-${month}-${day}`
    },

    //添加新用户
    addNewUser(formName) {

      //添加表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //设置添加时间
          this.getCurrentDate()

          //判断是调用新增接口还是编辑接口
          //如果是添加
          if (this.modalType === 0) {

            addUser(this.addUserForm).then(({data}) => {
              this.$message.success(data.message)
              this.getUserList()
            }).catch(() => {
              this.$message.error('添加失败')
            })

          } else {//是编辑功能

            //发送编辑请求
            editUser(this.addUserForm).then(({data}) => {
              this.$message.success(data.message)
              this.getUserList()
            }).catch(() => {
              this.$message.error('添加失败')
            })
          }


          //发送请求后关闭对话框
          this.dialogFormVisible = false

          //确定之后重置表单数据
          this.$refs.ruleForm.resetFields()
        } else {
          console.log('error submit')
          return false
        }
      })


    },
    //获取用户列表
    getUserList() {
      getUserData().then(({data}) => {
        this.tableData = data.data

      }, err => {
        console.log(err)
      })
      return this.tableData
    },
    //按姓名搜索的按钮点击事件
    handleSearchUserName(name) {
      this.tableData = this.tableData.filter((item) => {
        return item.name.includes(name)
      })
    },
    //清空表单数据
    handleClearUserName() {
      //重新发送请求获取数据
      this.getUserList()
    },
    //关闭对话框
    handleCancel() {
      this.$confirm('确认取消操作吗?您的用户数据还没有保存', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '已取消不再操作'
        });


        //重置表单数据
        // this.$refs.ruleForm.resetFields()
        this.dialogFormVisible = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '您可以继续修改啦'
        });
        this.dialogFormVisible = true
      });

      this.dialogFormVisible = false


    },
    //编辑当前行的数据
    handleEdit(index, item, modalType) {
      //打开对话框
      this.openDialog(modalType)

      //如果是编辑数据，则展示当前行的数据
      if (modalType === 1) {

        this.addUserForm = item
        console.log('原始数据', item)
      }


    },

    // 删除当前行的数据
    handleDelete(index, item) {
      deleteUser(item).then(() => {

        this.getUserList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.error('删除失败')
      })
    },


  },
  watch:{
    //todo: 编辑数据出现诡异的bug
    addUserForm:{
      deep:true,
      handler(newValue,oldValue){
        console.log('new',newValue)
        console.log('old',oldValue)
      }
    }
  }


}
</script>

<style scoped
       lang="less">
.user-container {
  margin: 15px auto;


  .user-dialog {
    height: 700px;
    width: 800px;
    margin: 100px auto;

    .user-form {
      padding-left: 50px;

      .user-form-name {
        width: 200px;
      }

      .user-form-address {
        width: 200px;
      }
    }

  }

  .user-func {
    display: flex;
    justify-content: space-between;


    //添加按钮
    .user-add {
      text-align: center;
      margin: 16px 10px;
    }

    //搜索框
    .user-search {
      display: flex;
      margin: 15px 10px;
      height: 30px;

      .user-search-form {

        display: flex;
        align-items: center;


        .el-form-item {
          margin: auto 10px;
          //搜索输入数据
          .user-search-data {

          }

          //搜索按钮
          .user-search-btn {

            text-align: center;
          }
        }


      }

    }
  }

  .user-table {
    height: 820px;
  }
}
</style>
